X

Node.js

Jwt in Cookie Authentication

September 20, 2022

/*

Why You Shouldn't use this Method


*/

Using a jwt in a cookie to authenticate a user comes with several risk such as cross site forgery, bloated or too much overhead in the token & xss(cross-site scripting) attack. Since I discovered these risk after I found out about this method, I learned how to do it, but I wouldn't recommend using it.

/*

Creating the Cookie & Token on Login


*/

We have a login route that we'll take a username & password. If the username & password are correct will create a cookie & a jwt. We'll put the jwt inside the cookie so it can be sent with the request. If the username & password are not correct, we'll redirect the user.

Creating the cookie & jwt on successful login

/*

Authenticating Routes


*/

We just got redirected to the dashboard. If the cookie is authenticated, we will grab the jwt inside & verify it. If they're both correct we'll display the dashboard. This authentication will be repeated for other routes like dashboard.

Authenticate the cookie & jwt

/*

Deleting the Cookie when the User Logs Out


*/

Last route will be the Logout route. There will be a link to it in the route pages such as dashboard. When we click the link we will destroy the cookie & access to the jwt.

Deleting the cookie & access to the jwt.


About the Author

Christopher Howard

Chris is a Javascript developer with a minor in UI design. He values programming in vanilla code. Fill out the form below to contact him.